'''
Created on Sep 26, 2012

@author: x220
'''
import cv2
import numpy as np


class DifferencesDetector(object):

    def __init__(self,background):
        self.background = background
      
    def get_contours(self,input_frame,threshold_value=60,gray=False,kernel=np.ones((5,5),'uint8'),number_of_iterations = 5,debug=False):
        if(gray):
            frame_gray = cv2.cvtColor(input_frame,cv2.COLOR_RGB2GRAY)
            frame_gray_background = cv2.cvtColor(self.background,cv2.COLOR_RGB2GRAY)
            frame_differences= cv2.absdiff(frame_gray_background, frame_gray)
        else:
            frame = input_frame
            frame_differences= cv2.absdiff(self.background, frame)
            
        frame_threshold = cv2.threshold(frame_differences, threshold_value, 255, cv2.THRESH_BINARY)[1]
        frame_dilate = cv2.dilate(frame_threshold, kernel,iterations=number_of_iterations)
        frame_erode = cv2.erode(frame_dilate,kernel,iterations=(2))
        if(gray):
            contours, temp = cv2.findContours(frame_erode,cv2.RETR_LIST ,cv2.CHAIN_APPROX_NONE)
        else:
            frame_gray = cv2.cvtColor(frame_erode,cv2.COLOR_RGB2GRAY)
            contours, temp = cv2.findContours(frame_gray,cv2.RETR_LIST  ,cv2.CHAIN_APPROX_NONE)
        
        if(debug):
            cv2.imshow('frame_differences',frame_differences)
            cv2.imshow('frame_threshold',frame_threshold)
            cv2.imshow('frame_dilate',frame_dilate)
            cv2.imshow('frame_erode',frame_erode)
            cv2.imshow('frame_gray',frame_gray)
        return contours
         
        
if __name__ == "__main__":
    im = cv2.imread('C:\\Users\\x220\\Desktop\\test.png')
    imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    ret,thresh = cv2.threshold(imgray,50,255,0)
    contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
    for x in contours:
        if(cv2.contourArea(x)  < 1000):
            for cor in x:
                cord =(cor[0][0],cor[0][1])
                cv2.line(im, cord, cord,(0,255,0),3)
  
    cv2.imshow('t',im)
    ch = 0
    while(ch != ord('q')):
        ch = cv2.waitKey(100)
